<template>
  <!-- <el-collapse accordion class="margin-bottom">
    <el-collapse-item>
      <template slot="title">
        <el-row style="width:100%" class="padding-lr">
          <i class="el-icon-copy-document text-lg"></i>
          <span class="text-df text-bold margin-left-sm">发票</span>
        </el-row>
      </template> -->
  <div class="padding">
    <el-card>
      <div slot="header" class="clearfix relative">
        <span class="title-icon">发票</span>
        <!-- <el-button
          type="success"
          size="mini"
          class="header-save-btn"
          @click="editInvoice"
        >
        
        </el-button> -->
      </div>

      <el-row class="margin-bottom-sm">
        <el-col :span="6">
          <span>ShipMentID:</span>
          <span>{{ shipmentId }}</span>
        </el-col>
        <el-col :span="6">
          <span>ReferenceID:</span>
          <span>{{ referenceId }}</span>
        </el-col>
        <el-col :span="6">
          <span>申报币种:</span>
          <span>{{ Constatvariable.declareValueCurrency }} </span>
        </el-col>
        <el-col :span="6">
          <el-row>
            <el-col
              v-if="
                Constatvariable.waybillNo &&
                  (Constatvariable.waybillNo.startsWith('AIR') ||
                    Constatvariable.waybillNo.startsWith('FCLG') ||
                    Constatvariable.waybillNo.startsWith('LCLG'))
              "
              :span="4"
              ><span>采购总价:</span>
            </el-col>
            <el-col :span="8">
              <el-input
                v-if="
                  Constatvariable.waybillNo &&
                    (Constatvariable.waybillNo.startsWith('AIR') ||
                      Constatvariable.waybillNo.startsWith('FCLG') ||
                      Constatvariable.waybillNo.startsWith('LCLG'))
                "
                type="text"
                size="mini"
                v-model="Constatvariable.totalPurchasingPrice"
              ></el-input>

              <span v-else>{{ Constatvariable.totalPurchasingPrice }}</span>
            </el-col>
            <el-col :span="2">
              <!-- 出库要锁定 -->
              <el-button
                v-if="
                  Constatvariable.status < 50 &&
                    this.Constatvariable.liquidationInvoices.length <= 0 &&
                    this.Constatvariable.packingLists.length <= 0
                "
                type="success"
                size="mini"
                style="margin-left:150px;"
                @click="changeTotalPurchasingPrice"
              >
                编辑
              </el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <TableModule
        :table-columns="tableColumns()"
        :table-data="invoiceData"
        need-serial-number
      />
    </el-card>

    <el-card class="margin-top">
      <div slot="header" class="clearfix relative">
        <span class="title-icon">箱单</span>
        <el-button
          class="margin-left"
          size="mini"
          type="success"
          @click="checkFbaNoNotInSub"
        >
          校验FBA箱号
        </el-button>

        <el-button
          class="margin-left"
          size="mini"
          type="success"
          @click="checkRepeatingInvoicePack"
        >
          校验重复箱单发票
        </el-button>
        <el-button
          class="margin-left"
          size="mini"
          type="success"
          @click="checkAndDeleteInvoicePack"
        >
          一键删除重复箱单发票
        </el-button>
      </div>
      <div
        class="margin-bottom-sm"
        v-for="(item, index) in boxData"
        :key="index"
      >
        <el-table
          :data="item.tableData"
          size="mini"
          border
          style="width: 100%"
          :span-method="objectSpanMethod"
        >
          <el-table-column label="箱号" prop="startNumNo">
            <template slot-scope="scope">
              <span :class="{ 'text-red': scope.row.isError }">
                {{ scope.row.startNumNo }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="单箱毛重(kg)" prop="weight">
          </el-table-column>
          <el-table-column label="单箱长×宽×高(cm)">
            <template slot-scope="scope">
              <span
                >{{ scope.row.length }} X {{ scope.row.width }} X
                {{ scope.row.height }}</span
              >
            </template>
          </el-table-column>
          <el-table-column prop="sku" label="SKU"> </el-table-column>
          <el-table-column prop="declareNameCn" label="中文品名">
          </el-table-column>
          <el-table-column prop="num" label="个数"> </el-table-column>
        </el-table>
      </div>
    </el-card>
    <CheckInvoicePack
      ref="checkInvoicePack"
      :packs="packs"
      :invoices="invoices"
    >
    </CheckInvoicePack>
  </div>
  <!-- </el-collapse-item>
  </el-collapse> -->
</template>

<script>
import { ajax } from "@/store/yg/common/utils";
import axios from "axios";
import * as constant from "@/store/yg/common/constant";
import { clone } from "@/utils/clone";
const TableModule = () => import("@/components/app/components/TableModule");
import CheckInvoicePack from "../components/CheckInvoicePack";

export default {
  props: {
    country: {
      type: String,
      default: ""
    },
    Constatvariable: {
      type: Object,
      default: function() {
        return {};
      }
    }
  },
  components: {
    TableModule,
    CheckInvoicePack
  },
  data() {
    return {
      isTotalPurchasingPrice: false,
      packs: [],
      invoices: [],
      isJap: false,
      shipmentId: "",
      referenceId: "",
      srcList: [],
      packingTableColumns: [
        { prop: "startNumNo", label: "箱号" },
        { prop: "weight", label: "单箱毛重(kg)" },
        { prop: "LWH", label: "单箱长×宽×高(cm)" },
        { prop: "sku", label: "SKU" },
        { prop: "declareNameCn", label: "中文品名" },
        { prop: "num", label: "个数" }
      ],
      invoiceData: [],
      boxData: {}
    };
  },

  methods: {
    changeTotalPurchasingPrice() {
      if (this.isTotalPurchasingPrice) {
        console.log("箱单长度", this.packs.length);
        if (this.Constatvariable.liquidationInvoices.length > 0) {
          this.$message.error("有箱单不能编辑");
          return;
        }
        if (this.Constatvariable.packingLists.length > 0) {
          this.$message.error("有发票不能编辑");
          return;
        }
        this.isTotalPurchasingPrice = false;
        var param = {};
        param["id"] = this.Constatvariable.id;
        param[
          "totalPurchasingPrice"
        ] = this.Constatvariable.totalPurchasingPrice;
        param["key"] = "buy";
        ajax("changeHInfo", param).then(
          res => {
            console.log(res);
            if (res.code != 200) {
              this.$message.error(res.message);
            } else {
              console.log(res.data);
            }
          },
          error => {
            console.log(error);
          }
        );
      } else {
        this.isTotalPurchasingPrice = true;
      }
    },
    tableColumns() {
      let list = [
        { prop: "shipmentId", label: "ShipmentID" },
        { prop: "referenceId", label: "ReferenceID" },
        { prop: "sku", label: "SKU" },
        { prop: "declareNameEn", label: "英文品名" },
        { prop: "declareNameCn", label: "中文品名" },
        { prop: "brand", label: "品牌" },
        { prop: "model", label: "型号" },
        { prop: "material", label: "材质" },
        { prop: "purpose", label: "用途" },
        { prop: "customsCode", label: "出口报关编码" },
        { prop: "customsClearanceCode", label: "清关编码" },
        { prop: "asin", label: "ASIN" },
        { prop: "num", label: "数量" },
        { prop: "measurementUnit", label: "单位" },
        { prop: "perSuitNum", label: "每套个数" },
        { prop: "isCharged", label: "是否带电" },
        { prop: "purchasingPrice", label: "采购单价¥" }
      ];
      const noJapList = [
        {
          prop: "declareValue",
          label: `申报单价`
        },
        { prop: "imgUrl", label: "图片", type: "img" }
      ];
      const japList = [
        { prop: "declareValue", label: "ASIN售价" },
        { prop: "distributionMaterialCount", label: "配送料" },
        { prop: "productLotCount", label: "出品手数料" },
        { prop: "imgUrl", label: "图片", type: "img" },
        { prop: "sellpriceScreenshot", label: "售价截图", type: "img" },
        { prop: "incomeScreenshot", label: "收益截图", type: "img" }
      ];

      if (
        this.waybillInfo &&
        this.waybillInfo.liquidationInvoice &&
        this.waybillInfo.liquidationInvoice.length > 0 &&
        this.waybillInfo.liquidationInvoice.isCharged
      ) {
        list.splice(
          12,
          0,
          { prop: "volt", label: "电压(伏特)" },
          { prop: "milliampere", label: "电容(毫安)" },
          { prop: "watt", label: "功率(瓦特)" }
        );
      }

      if (this.country && this.country.indexOf("日本") != -1) {
        list = [...list, ...japList];
      } else {
        list = [...list, ...noJapList];
      }
      return list;
    },
    addImages(imageUrl) {
      this.srcList = [];
      this.srcList.push(imageUrl);
    },
    // 合并列
    // objectSpanMethod({ row, column, rowIndex, columnIndex }) {
    //   //rowIndex：行    columnIndex：列
    //   if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2) {
    //     // 如果这个已经展示了，就不要再展示
    //     if (row.showData) {
    //       return {
    //         rowspan: this.tempDetailsList[this.boxData[rowIndex].startNumNo],
    //         colspan: 1
    //       };
    //     } else {
    //       return {
    //         rowspan: 0,
    //         colspan: 0
    //       };
    //     }
    //   }
    // },

    checkRepeatingInvoicePack() {
      var param = {};
      param["id"] = this.$route.query.waybillId;
      ajax("checkRepeatingInvoicePack", param).then(
        res => {
          console.log(res);
          if (res.code != 200) {
            this.$message.error("系统错误");
          } else {
            this.packs = res.data2;
            this.invoices = res.data;
            this.$refs.checkInvoicePack.centerDialogVisible = true;
          }
        },
        error => {
          console.log(error);
        }
      );
    },

    checkAndDeleteInvoicePack() {
      var param = {};
      param["id"] = this.$route.query.waybillId;
      this.$confirm("此操作将所有重复箱号删除是否继续？").then(_ => {
        ajax("checkAndDeleteInvoicePack", param).then(
          res => {
            console.log(res);
            if (res.code != 200) {
              this.$message.error("系统错误");
            } else {
              this.$message.success("所有重复箱号都已删除!");
            }
          },
          error => {
            console.log(error);
          }
        );
      });
    },

    checkFbaNoNotInSub() {
      var param = {};
      param["id"] = this.$route.query.waybillId;
      ajax("checkFbaNoNotInSub", param).then(
        res => {
          console.log(res);
          if (res.code != 200) {
            this.$message.error("系统错误");
          } else {
            if (res.data) {
              // $.each(data.fbaNos,function(i,n){
              // 	$('tr[name="'+n+'"]').find('td:eq(0)').css('color','#FF7575');
              // })
              // this.$message.error(res.data);
              this.setRed(res.data);
            } else {
              this.$message.success("所有箱号都已匹配上!");
            }
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    setRed(list) {
      let arr = [];
      if (Object.prototype.toString.call(list) === "[object String]") {
        arr = list.split(",");
      } else if (Object.prototype.toString.call(list) === "[object Array]") {
        arr = list;
      }
      for (const i of this.boxData) {
        for (const j of i.tableData) {
          this.$delete(j, "isError");
          this.$set(j, "isError", false);
          const target = arr.find(x => x === j.startNumNo);
          // console.log("target :>> ", target);
          if (target) {
            this.$delete(j, "isError");
            this.$set(j, "isError", true);
          }
          // console.log("j :>> ", j);
        }
      }
    },
    editInvoice() {},
    showAll() {
      var param = {};
      const waybillId = this.$route.query.waybillId;
      param["waybillId"] = waybillId;
      ajax("fetchPackingList", param).then(
        res => {
          if (res.code != 200) {
            this.$message.error(res.message);
          } else {
            if (null != res.data) {
              this.invoiceData = res.data;
              this.invoiceData.forEach(element => {
                // if (element.isCharged == 0) {
                //   element.isCharged = "否";
                // } else if (element.isCharged == 1) {
                //   element.isCharged = "是";
                // }
              });
            }
            if (null != res.data4) {
              const arr = [];
              for (const i of res.data4) {
                for (const j of i.packSkuList) {
                  let obj = {
                    sku: j.sku,
                    declareNameCn: j.declareNameCn,
                    num: j.num,
                    startNumNo: i.startNumNo,
                    weight: i.weight,
                    length: i.length,
                    width: i.width,
                    height: i.height,
                    shipmentId: i.startNumNo.slice(
                      0,
                      i.startNumNo.lastIndexOf("U")
                    )
                  };

                  arr.push(obj);
                }
              }
              let dataArr = [];
              arr.map(mapItem => {
                if (dataArr.length == 0) {
                  dataArr.push({
                    shipmentId: mapItem.shipmentId,
                    tableData: [mapItem]
                  });
                } else {
                  let res = dataArr.some(item => {
                    //判断相同日期，有就添加到当前项
                    if (item.shipmentId == mapItem.shipmentId) {
                      item.tableData.push(mapItem);
                      return true;
                    }
                  });
                  if (!res) {
                    //如果没找相同日期添加一个新对象
                    dataArr.push({
                      shipmentId: mapItem.shipmentId,
                      tableData: [mapItem]
                    });
                  }
                }
              });

              // this.boxData.tableData = arr;
              this.boxData = dataArr;

              for (const i of this.boxData) {
                this.getSpanArr(i);
              }
            }
            if (null != res.data2) {
              this.shipmentId = res.data2;
            }
            if (null != res.data3) {
              this.referenceId = res.data3;
            }
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    // 计算表格合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2) {
        const target = this.boxData.find(x => x.shipmentId === row.shipmentId);
        return {
          rowspan: target ? target.spanArr[rowIndex] : 1,
          colspan: 1
        };
      }
    },
    async getSpanArr(obj) {
      // 数据排序，以便合并

      if (obj && obj.tableData && obj.tableData.length > 0) {
        let spanArr = [];
        let pos = 0;

        obj.tableData.sort(
          (a, b) =>
            a.startNumNo.slice(a.startNumNo.lastIndexOf("U") + 1) -
            b.startNumNo.slice(a.startNumNo.lastIndexOf("U") + 1)
        );
        spanArr = [];
        pos = 0;
        for (var i = 0; i < obj.tableData.length; i++) {
          obj.tableData[i].isError = false;
          if (i === 0) {
            spanArr.push(1);
            pos = 0;
          } else {
            // 判断当前元素与上一个元素是否相同,因合并第一个所以[0]

            if (
              obj.tableData[i]["startNumNo"] ===
              obj.tableData[i - 1]["startNumNo"]
            ) {
              spanArr[pos] += 1;
              spanArr.push(0);
            } else {
              spanArr.push(1);
              pos = i;
            }
          }
        }
        obj.spanArr = clone(spanArr);
        obj.pos = clone(pos);
        return obj;
      }
    }
  },
  mounted() {
    this.showAll();
    this.tableColumns();
  }
};
</script>

<style></style>
